const Koa = require('koa'),
  app = new Koa(),
  views = require('koa-views'),
  json = require('koa-json'),
  onerror = require('koa-onerror'),
  bodyparser = require('koa-bodyparser'),
  logger = require('koa-logger'),
  session = require('koa-session'),
  user = require('./routes/user'),
  permission = require('./routes/permission'),
  loan = require('./routes/loan'),
  approve = require('./routes/approve'),
  contract = require('./routes/contract'),
  {
    checkLogin
  } = require('./middlewares');


//退出后的token
app.context.blackTokenList = []


// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
  }))
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(__dirname + '/views', {
    extension: 'pug'
  }))

  // logger
  .use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  })
const store = {
  storage: {},
  set(key, session) {
    //生成session内置的key
    this.storage[key] = session
    //也可以存储到数据库
  },
  get(key) {
    //也可以从数据库中获取
    return this.storage[key]
  },
  destroy(key) {
    delete this.storage[key]
    //也可以从数据库中删除该session释放空间
  }
}
//响应处理
app.context.success = function (data) {
  this.body = {
    code: 20000, //成功
    data
    // msg 
  }
}
app.context.faild = function (data) {
  this.body = {
    code: 102, //失败
    data
    // msg
  }
}
app.context.tokenExpires = function (data) {
  this.body = {
    code: 603, //权限有问题，需要重定向
    data
    // msg
  }
}
//登录验证
app.use(checkLogin)

  // 处理session
  .use(session({
    store
  }, app))

  // routes
  .use(user.routes(), user.allowedMethods())
  .use(permission.routes(), permission.allowedMethods())
  .use(loan.routes(), loan.allowedMethods())
  .use(approve.routes(), approve.allowedMethods())
  .use(contract.routes(), contract.allowedMethods())

// error-handling
.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app